package com.itheima.dubbo.api;

import com.itheima.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;



    //建立好友关系（双向，先判断是否已是好友）
    @Override
    public void save(Long userId, Long friendId) {
        //保存好友数据
        if(!mongoTemplate.exists(Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId)), Friend.class)){
            //不是好友就保存好友
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

        if(!mongoTemplate.exists(Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId)), Friend.class)){
            //不是好友就保存好友
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }

    @Override
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        return mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)).with(PageRequest.of(page-1,pagesize, Sort.by(Sort.Order.desc("created")))), Friend.class);
    }
    //删除好友关系
    @Override
    public void delete(Long userId, Long friendId) {
        //删除好友数据
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        if(mongoTemplate.exists(query, Friend.class)){
            //是好友就删除好友
            mongoTemplate.remove(query, Friend.class);
        }
        Query query1 = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        if(mongoTemplate.exists(query1, Friend.class)){
            //是好友就删除好友
            mongoTemplate.remove(query1, Friend.class);
        }
    }
    /*判断是否是好友关系*/
    @Override
    public boolean isFriend(Long userId, Long friendId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        return mongoTemplate.exists(query, Friend.class);
    }

}
